#include <qstring.h>

#include <iostream>
using namespace std;

#include "dbcheck.h"

#include "mythtv/mythcontext.h"
#include "mythtv/mythdbcon.h"

#include "cdgsettings.h"

const QString currentDatabaseVersion = "1000";

static bool UpdateDBVersionNumber(const QString &newnumber)
{
    // delete old schema version
    MSqlQuery query(MSqlQuery::InitCon());

    QString thequery = "DELETE FROM settings WHERE value='CDGDBSchemaVer';";
    query.prepare(thequery);
    query.exec();

    if (query.lastError().type() != QSqlError::None)
    {
        QString msg =
            QString("DB Error (Deleting old DB version number): \n"
                    "Query was: %1 \nError was: %2 \nnew version: %3")
            .arg(thequery)
            .arg(MythContext::DBErrorMessage(query.lastError()))
            .arg(newnumber);
        VERBOSE(VB_IMPORTANT, msg);
        return false;
    }

    // set new schema version
    thequery = QString("INSERT INTO settings (value, data, hostname) "
                          "VALUES ('CDGDBSchemaVer', %1, NULL);")
                         .arg(newnumber);
    query.prepare(thequery);
    query.exec();

    if (query.lastError().type() != QSqlError::None)
    {
        QString msg =
            QString("DB Error (Setting new DB version number): \n"
                    "Query was: %1 \nError was: %2 \nnew version: %3")
            .arg(thequery)
            .arg(MythContext::DBErrorMessage(query.lastError()))
            .arg(newnumber);
        VERBOSE(VB_IMPORTANT, msg);
        return false;
    }

    return true;
}

static bool performActualUpdate(const QString updates[], QString version,
                                QString &dbver)
{
    MSqlQuery query(MSqlQuery::InitCon());

    VERBOSE(VB_IMPORTANT, QString("Upgrading to MythCDG schema version ") + 
            version);

    int counter = 0;
    QString thequery = updates[counter];

    while (thequery != "")
    {
        query.prepare(thequery);
        query.exec();

        if (query.lastError().type() != QSqlError::None)
        {
            QString msg =
                QString("DB Error (Performing database upgrade): \n"
                        "Query was: %1 \nError was: %2 \nnew version: %3")
                .arg(thequery)
                .arg(MythContext::DBErrorMessage(query.lastError()))
                .arg(version);
            VERBOSE(VB_IMPORTANT, msg);
            return false;
        }

        counter++;
        thequery = updates[counter];
    }

    if (!UpdateDBVersionNumber(version))
        return false;

    dbver = version;
    return true;
}

bool InitializeDatabase(void)
{
    VERBOSE(VB_IMPORTANT, "Inserting MythCDG initial database information.");

    const QString updates[] = {
"CREATE TABLE cdgmetadata ("
"  type VARCHAR(10) NOT NULL default '',"
"  name VARCHAR(128) NOT NULL default '',"
"  title VARCHAR(128) NOT NULL default '',"
"  filepath VARCHAR(255) NOT NULL default '',"
"  containerpath VARCHAR(255) NOT NULL default '',"
"  hostname VARCHAR(255),"
"  KEY ktype (type),"
"  KEY kname (name)"
");",
""
};
    QString dbver = "";
    if (!performActualUpdate(updates, "1000", dbver))
        return false;

    return true;
}

bool UpgradeCDGDatabaseSchema(void)
{
    QString dbver = gContext->GetSetting("CDGDBSchemaVer");
    MSqlQuery query(MSqlQuery::InitCon());
   
    if (dbver == currentDatabaseVersion)
        return true;

    if (dbver == "")
    {
        if (!InitializeDatabase())
            return false;
        dbver = "1000";
    }


    return true;
}
